package com.iwhalecloud.citybrain.flow.platform.manager.application.service.impl.task;

import com.iwhalecloud.citybrain.flow.platform.manager.application.service.CustomEventHandler;
import com.iwhalecloud.citybrain.flow.platform.manager.domain.exception.EventCallSuspendException;
import com.iwhalecloud.citybrain.flow.platform.manager.domain.model.monitor.FlowTaskTraceVo;
import com.iwhalecloud.citybrain.flow.platform.manager.domain.repository.FlowTaskTraceRepository;
import lombok.extern.slf4j.Slf4j;
import org.flowable.engine.common.api.delegate.event.FlowableEngineEventType;
import org.flowable.engine.common.api.delegate.event.FlowableEvent;
import org.flowable.engine.common.api.delegate.event.FlowableEventType;
import org.flowable.engine.delegate.event.impl.FlowableEntityEventImpl;
import org.flowable.task.service.impl.persistence.entity.TaskEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @author: niechanggang
 * @date:2021/8/18 10:37
 * @description:
 */
@Slf4j
@Component
public class TaskAssignHandler  implements CustomEventHandler {

    @Autowired
    private FlowTaskTraceRepository  flowTaskTraceRepository;

    @Override
    public FlowableEventType getEventType() {
        return FlowableEngineEventType.TASK_ASSIGNED;
    }

    @Override
    public void handle(FlowableEvent event) throws EventCallSuspendException {
        if (!FlowableEntityEventImpl.class.isAssignableFrom(event.getClass())) {
            return;
        }
        FlowableEntityEventImpl entityEvent = (FlowableEntityEventImpl) event;
        TaskEntity taskEntity = (TaskEntity) entityEvent.getEntity();
        String taskId = taskEntity.getId();
        String  assignee = taskEntity.getAssignee();
        FlowTaskTraceVo flowTaskTraceVo = new FlowTaskTraceVo();
        flowTaskTraceVo.setTaskId(taskId);
        flowTaskTraceVo.setAssignee(assignee);
        flowTaskTraceRepository.updateAssignInfoByTaskId(flowTaskTraceVo);
        log.info("Change Task Assign, TaskId:"+taskId+" Assignee:"+assignee);
    }
}
